<template>
  <view class="container" style="paddingBottom:1rpx;">
    <u-navbar
    leftIconSize="40rpx"
    leftIconColor="#333333"
    title="物价记录"
  >
  </u-navbar>
    <view class="section">
      <view class="section-title">{{ title}}</view>
      <view class="form-view">
        <u--form labelPosition="left" :model="form" :rules="rules" ref="uForm" label-width="auto"
          :labelStyle="{ color: '#333333', fontSize: '30rpx' }">
          <u-form-item label="商品类别" prop="categoryName" required @click="handleCategory">
            <u--input v-model="form.categoryName" disabled disabledColor="#ffffff" placeholder="请选择商品类别"
              inputAlign="right" border="none"></u--input>
            <u-icon slot="right" name="arrow-down"></u-icon>
          </u-form-item>
          <u-form-item label="商品名称" prop="productName" required @click="handleProductName">
            <u--input v-model="form.productName" disabled disabledColor="#ffffff" placeholder="请选择商品名称"
              inputAlign="right" border="none"></u--input>
            <u-icon slot="right" name="arrow-down"></u-icon>
          </u-form-item>
          <u-form-item label="子类别" prop="kind" required >
            <u--input v-model="form.kind"  placeholder="请填写子类别"
              inputAlign="right" border="none"></u--input>
          </u-form-item>
          <u-form-item label="价格" prop="price" required >
            <u--input v-model="form.price" type="number" placeholder="请填写价格"
              inputAlign="right" border="none"></u--input>
          </u-form-item>
          <u-form-item label="单位" prop="unitName" required @click="handleUnit">
            <u--input v-model="form.unitName" disabled disabledColor="#ffffff" placeholder="请选择单位"
              inputAlign="right" border="none"></u--input>
            <u-icon slot="right" name="arrow-down"></u-icon>
          </u-form-item> 
          <u-form-item label="记录时间" prop="recordTime" required @click="selectDate()">
            <u--input v-model="form.recordTime" disabled disabledColor="#ffffff" placeholder="请选择记录时间" inputAlign="right" border="none"></u--input>
          <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          <u-form-item label="地点" prop="address"  >
            <u--input v-model="form.address"  placeholder="请填写地点"
              inputAlign="right" border="none"></u--input>
          </u-form-item>
          <u-form-item label="商家" prop="merchant"  >
            <u--input v-model="form.merchant"  placeholder="请填写商家"
              inputAlign="right" border="none"></u--input>
          </u-form-item>
          <u-form-item label="备注" prop="remark"  labelPosition="top">
            <u--textarea v-model="form.remark" placeholder="请填写备注" border="none" autoHeight inputAlign="right" count
              maxlength="20000" style="padding:18rpx 0;"></u--textarea>
          </u-form-item>
        </u--form>
        <view class="form-btn">
          <u-button type="primary" text="提交" @click="submit"></u-button>
        </view>
      </view>
    </view>
    <u-toast ref="uToast"></u-toast>
    <u-picker itemHeight="88" :show="showCategory" :columns="categoryTypeList" keyName="dictLabel" @cancel="handleCategoryCancel"
      @confirm="handleCategoryConfirm"></u-picker>
      <u-picker itemHeight="88" :show="showProductName" :columns="productNameList" keyName="name" @cancel="handleProductNameCancel"
      @confirm="handleProductNameConfirm"></u-picker>
      <u-picker itemHeight="88" :show="showUnit" :columns="unitList" keyName="dictLabel" @cancel="handleUnitCancel"
      @confirm="handleUnitConfirm"></u-picker>
      <u-datetime-picker
    :show="datePickShow"
    mode="datetime"
    ref="recordTimeRef" 
    @cancel="datePickShow=false"
    @confirm="datePickConfirm"
    itemHeight="88"
  ></u-datetime-picker>
  </view>
</template>

<script setup>
import {getProductPriceRecord, addProductPriceRecord, updateProductPriceRecord } from '@/api/invest/productPriceRecord'
import { getDicts } from '@/api/system/dict/data.js'
import { listProductInfor } from '@/api/invest/productInfor'
const { proxy } = getCurrentInstance()
import dayjs from 'dayjs'
import {onLoad,onReady} from "@dcloudio/uni-app";
  // 计算属性与监听属性是在vue中而非uniap中 需要注意！！！
import {reactive ,toRefs,ref,computed ,getCurrentInstance }from "vue";
const datePickShow = ref(false)

const showCategory = ref(false)
const showProductName = ref(false)
const showUnit = ref(false)

const title = ref("物价记录")
const categoryTypeList = ref([])
const productNameList = ref([])

const flag = ref('add')
const unitList = ref([])
const data = reactive({
form: {
  id: null,
    productId: null,
    price: null,
    recordTime: null,
    remark: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updatedBy: null,
    address: null,
    delFlag: null,
    merchant: null,
    fields: null,
    unit: null,
    kind: null,
    category: null
},
queryProductParams: {
  pageNum: 1,
  pageSize: 1000
},
rules: {
  categoryName: [{ required: true, message: '商品类别不能为空', trigger:['change', 'blur'] }],
  productName: [{ required: true, message: '商品名称不能为空', trigger: ['change', 'blur'] }],
  price: [{type: 'number', required: true, message: '价格不能为空', trigger: ['change', 'blur'] }],
  unitName: [{ required: true, message: '单位不能为空', trigger:['change', 'blur'] }],
  kind: [{ required: true, message: '子类别不能为空', trigger: ['change', 'blur'] }],
  recordTime: [{ required: true, message: '记录时间不能为空', trigger: ['change', 'blur'] }]
}
})
const { form, queryProductParams, rules} = toRefs(data)


onLoad((option) => {
     form.value.id = option.id
     flag.value = option.flag
     if(flag.value==null){
      if(form.value.id!=null){
      title.value="物价记录-修改"
     }else{
      title.value="物价记录-新增"
     }
     }else{
      title.value="物价记录-复制"
     }
   
})
onReady(() => {
  form.value.recordTime = dayjs(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
  getData()
})
function  getData() {
 
      // 类型
      getDicts('product_category').then(res => {
      categoryTypeList.value =[res.data] 
    })
     // 类型
     getDicts('product_unit').then(res => {
      unitList.value =[res.data] 
    })

  
    if(form.value.id!=null){
      getProductPriceRecord(form.value.id).then(res => {
        form.value = res.data
        queryProductParams.value.category = form.value.category
       if(queryProductParams.value.category!=null){
      listProductInfor(queryProductParams.value).then((response) => {
        productNameList.value = [response.rows] 
       })   } 
        
       // 记账类型
       getDicts('product_category').then(result => {
        form.value.categoryName=dictStr(form.value.category, result.data)
       })
              // 交易类型
              getDicts('product_unit').then(result => {
        form.value.unitName=dictStr(form.value.unit, result.data)
       })
       if(flag.value!=null){
        form.value.recordTime = dayjs(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
       }

      })
    }else {
      listProductInfor(queryProductParams.value).then((response) => {
  productNameList.value = [response.rows] 
})
    }
}
function dictStr(val, arr) {
    let str = ''
    arr.map(item => {
      if (item.dictValue === val) {
        str = item.dictLabel
      }
    })
    return str
  }

function handleCategory() {
      if (categoryTypeList.value[0].length === 0) {
        proxy.$refs['uToast'].show({
          message: '商品类别为空  ', type: 'warning'
        })
      } else {
        showCategory.value = true
      }
   }
function   handleCategoryConfirm(e) {
      form.value.categoryName = e.value[0].dictLabel
      form.value.category = e.value[0].dictValue
      queryProductParams.value.category = form.value.category
      form.value.productId = null
      form.value.productName = null
      form.value.kind = null
      form.value.unit = null
      form.value.unitName = null
      form.value.price = null
      listProductInfor(queryProductParams.value).then((response) => {
        productNameList.value = [response.rows] 
       })

     
      showCategory.value = false
      
}
function handleCategoryCancel() {
     showCategory.value = false
    }
    function handleProductName() {
      if (productNameList.value[0].length === 0) {
        proxy.$refs['uToast'].show({
          message: '商品名称为空  ', type: 'warning'
        })
      } else {
        showProductName.value = true
      }
   }
function   handleProductNameConfirm(e) {
      form.value.productName = e.value[0].name
      form.value.kind = e.value[0].name
      form.value.productId = e.value[0].id
      form.value.unit = e.value[0].unit
       // 单位
       getDicts('product_unit').then(result => {
          form.value.unitName=dictStr( form.value.unit, result.data)
         })
      showProductName.value = false
}
function handleProductNameCancel() {
     showProductName.value = false
}


function handleUnit() {
      if (unitList.value[0].length === 0) {
        proxy.$refs['uToast'].show({
          message: '单位为空  ', type: 'warning'
        })
      } else {
        showUnit.value = true
      }
   }
function   handleUnitConfirm(e) {
      form.value.unitName = e.value[0].dictLabel
      form.value.unit = e.value[0].dictValue
      showUnit.value = false
}
function handleUnitCancel() {
     showUnit.value = false
    }
function  selectDate() {
      datePickShow.value = true
      proxy.$refs['recordTimeRef'].innerValue = new Date().getTime()
  }
function datePickConfirm(e) {
      form.value.recordTime = dayjs(e.value).format("YYYY-MM-DD HH:mm:ss")
      datePickShow.value = false
  }
function submit() {
      proxy.$refs['uForm'].validate().then(() => {
        if (form.value.id != null) {
          if(flag.value==null){
            updateProductPriceRecord(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '修改成功', complete() {
              uni.navigateTo({ url: `/pages/work/product/productPriceRecord/list` })
            }
          })
        })
          }else {
            form.value.id == null
            addProductPriceRecord(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '新增成功', complete() {
              uni.navigateTo({ url: `/pages/work/product/productPriceRecord/list` })
            }
          })
        })
          }
        }else {
          addProductPriceRecord(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '新增成功', complete() {
              uni.navigateTo({ url: `/pages/work/product/productPriceRecord/list` })
            }
          })
        })
        }
      })
    }
</script>

<style lang="scss" scoped>
.section {
  margin: 24rpx;
  padding: 16rpx 24rpx;
  background-color: #fff;
  border-radius: 8rpx;

  .section-title {
    width: 360rpx;
    color: #333333;
    line-height: 44rpx;
    font-size: 30rpx;
    border-left: 6rpx solid #2681FF;
    padding-left: 26rpx;
  }

  .form-view {
    padding: 20rpx 0rpx 0 10rpx;

    .form-btn {
      padding-top: 20rpx;
    }
  }
}
</style>